package pcf8591

import (
	"fmt"
	"log"
	"periph.io/x/conn/v3/i2c/i2creg"
	"periph.io/x/host/v3"
	"time"
)

func main() {
	// 加载所有驱动
	if _, err := host.Init(); err != nil {
		log.Fatal(err)
	}

	// 打开第一个可用I²C总线的handle
	bus, err := i2creg.Open("/dev/i2c-1")
	//bus, err := i2creg.Open("")
	if err != nil {
		log.Fatal(err)
		return
	}
	defer bus.Close()

	// 通过执行命令 'sudo i2cdetect -y 1' 查看 PCF8591 设备地址
	dev, err := NewI2C(bus, 0x48)
	if err != nil {
		log.Fatal(err)
		return
	}

	run := true
	go func() {
		for run {
			v := dev.Read(AIO0)
			v1 := dev.Read(AIO1)
			v2 := dev.Read(AIO2)
			log.Println(fmt.Sprintf("v = %d,\tv1 = %d,\tv2 = %d", v, v1, v2))
			time.Sleep(100)
		}
	}()
	defer func() {
		run = false
	}()
	time.Sleep(20 * time.Second)
}

// Uint16ToBytes unit16 -> bytes
func Uint16ToBytes(n uint16) []byte {
	return []byte{
		byte(n),
		byte(n >> 8),
	}
}

// BytesToUint16 bytes -> unit16
func BytesToUint16(array []byte) uint16 {
	var data uint16 = 0
	for i := 0; i < len(array); i++ {
		data = data + uint16(uint(array[i])<<uint(8*i))
	}

	return data
}
